package de.joergviola.mobj.client.database;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.google.code.gwt.database.client.SQLTransaction;
import com.google.gwt.user.client.rpc.AsyncCallback;

import de.joergviola.mobj.shared.Entity;
import de.joergviola.mobj.shared.KeyNotUniqueException;
import de.joergviola.mobj.shared.ObjectNotFoundException;
import de.joergviola.mobj.shared.Persistable;
import de.joergviola.mobj.shared.Schema;

public class Get<T extends Persistable> extends Select<T> {

	private static final Logger log = Logger.getLogger("Get");

	public Get(Schema schema, Entity<T> entity) {
		super(schema, entity, getIdWhere(entity));
	}

	private static String getIdWhere(Entity<? extends Persistable> entity) {
		return entity.getFieldnames()[0] + "=?";
	}

	public void execute(SQLTransaction tx, final Long id,
			final AsyncCallback<T> callback) {
		setArgs(new Object[] { id });
		super.execute(tx, new AsyncCallback<List<T>>() {

			@Override
			public void onFailure(Throwable caught) {
				log.log(Level.SEVERE, "", caught);
				callback.onFailure(caught);
			}

			@Override
			public void onSuccess(List<T> result) {
				if (result.size() == 0) {
					log.info("Object not found");
					callback.onFailure(new ObjectNotFoundException(id));
				} else if (result.size() > 1) {
					log.info("Non-unique key");
					callback.onFailure(new KeyNotUniqueException(id, result
							.size()));
				} else {
					callback.onSuccess(result.get(0));
				}
			}
		});
	}

}
